from utils.utils import *
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from config.config import *
from utils.data_split import *


# 临床的不必要侵入性手术

clinic_data = pd.read_csv(patient_original_data_path,encoding="gbk")
dp = DataSplitUtil(split_random_state=split_random_state_list[0])
clinic_train_df,clinic_test_df = dp.get_train_test_df(clinic_data)

# 补充QL数据集到test_df
clinic_test_df["ALN status simplified"] = clinic_test_df["ALN status"].replace({
    "N+(1-2)": "N+",
    "N+(>2)": "N+"
})
count_table = pd.crosstab(clinic_test_df["Surgical"], clinic_test_df["ALN status simplified"])

# 占比
prop_table = pd.crosstab(clinic_test_df["Surgical"], clinic_test_df["ALN status simplified"], normalize="index")

# 合并展示
result = count_table.astype(str) + " (" + (prop_table*100).round(1).astype(str) + "%)"
print(result)




# 模型的临床效益


best_threshold_by_youden = 0.4291484596852248

model = joblib.load(opj(ensemble_model_weight_path,'model.joblib'))
data = pd.read_csv(signature_score_csv_path)
signature_train_df,signature_test_df = dp.get_train_test_df(data)
signature_test_X = signature_test_df.drop(columns=exclude_columns)
signature_test_Y = signature_test_df[target_column]
test_avg_proba = model.predict_proba_by_dif(signature_test_X)[:, 1]
y_pred = (test_avg_proba >= best_threshold_by_youden).astype(int)

df = pd.DataFrame({"y_true": signature_test_Y, "y_pred": y_pred})

# 总体预测统计
summary = df["y_pred"].value_counts().rename_axis("Predicted").reset_index(name="Count")
summary["Proportion"] = (summary["Count"] / summary["Count"].sum() * 100).round(2).astype(str) + "%"

# 真实标签分布
cross = df.groupby("y_pred")["y_true"].value_counts().unstack(fill_value=0)
cross.columns = ["Actual_N0", "Actual_N+"]

# 合并
final = summary.merge(cross, left_on="Predicted", right_index=True)

# 加上比例
final["Actual_N0_%"] = (final["Actual_N0"] / final["Count"] * 100).round(2).astype(str) + "%"
final["Actual_N+_%"] = (final["Actual_N+"] / final["Count"] * 100).round(2).astype(str) + "%"

print(final)

n = 284


import matplotlib.pyplot as plt
from matplotlib.ticker import PercentFormatter
# 你指定的柱状图高度 (0~1之间)
values = [0.613, 0.176]  
labels = ['Invasive Surgery', 'iTME-ALN']  # 每根柱子的标签
percentages = [v * 100 for v in values]
plt.figure(figsize=(5, 5))
plt.bar(labels, percentages, color=[(75/255, 116/255, 178/255),(219/255, 49/255, 36/255)], width=0.5)

# 在柱子上标注数值
for i, p in enumerate(percentages):
    plt.text(i, p + 0.02, f"{p:.1f}%({int(round(p * 0.01 * n))})", ha='center', va='bottom')
plt.gca().yaxis.set_major_formatter(PercentFormatter())
plt.ylim(0, 100)   # y轴范围锁定在0-1
plt.title("Rate of unneccessary invasive surgery")
md(clinic_benefit_result_path)
plt.savefig(opj(clinic_benefit_result_path,'Rate of unneccessary invasive surgery.pdf'))
plt.close()




values = [0.387, 0.711]  
labels = ['Invasive Surgery', 'iTME-ALN']  # 每根柱子的标签
percentages = [v * 100 for v in values]
plt.figure(figsize=(5, 5))
plt.bar(labels, percentages, color=[(75/255, 116/255, 178/255),(219/255, 49/255, 36/255)], width=0.5)
# 在柱子上标注数值
for i, p in enumerate(percentages):
    plt.text(i, p + 0.02, f"{p:.1f}%({int(round(p * 0.01 * n))})", ha='center', va='bottom')
plt.gca().yaxis.set_major_formatter(PercentFormatter())
plt.ylim(0, 100)   # y轴范围锁定在0-1
plt.title("Rate of of benefit")
md(clinic_benefit_result_path)
plt.savefig(opj(clinic_benefit_result_path,'Rate of benefit.pdf'))
plt.close()